//
//  RegisterViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/3/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "RegisterViewController.h"
#import "InstructionViewController.h"
#import "TermsOfServiceViewController.h"
#import "GruphotoAppDelegate.h"
#import "User.h"

#define kLabelTag 4096
#define kEmailIndex     0
#define kPasswordIndex  1
#define kFirstNameIndex 2
#define kLastNameIndex  3
#define kPhoneIndex     4

@interface RegisterViewController ()
- (void)resignKeyboard;
@end

@implementation RegisterViewController
@synthesize emailTextField, passwordTextField, firstNameTextField, lastNameTextField, phoneTextField, addPhotoButton;
@synthesize descriptionLabel, termsOfServiceLabel, registerScrollView, editMode;
@synthesize avatar;

#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {              
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
        self.navigationItem.leftBarButtonItem = cancelButtonItem;
        [cancelButtonItem release];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [editButton setBounds:CGRectMake(0, 0, 51, 30)];
    if (editMode == AccountEditModeRegister) {
        [editButton setBackgroundImage:[UIImage imageNamed:@"button_create.png"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(createButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    else { // Edit mode update
        [editButton setBackgroundImage:[UIImage imageNamed:@"button_done.png"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    UIBarButtonItem *editButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
    self.navigationItem.rightBarButtonItem = editButtonItem;
    [editButtonItem release];
    
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    descriptionLabel.textColor = [UIColor colorWithRed:76/255.0 green:86/255.0 blue:108/255.0 alpha:1.0];
    termsOfServiceLabel.textColor = [UIColor colorWithRed:72/255.0 green:138/255.0 blue:198/255.0 alpha:1.0];
    registerScrollView.contentSize = CGSizeMake(320, registerScrollView.frame.size.height + 200);
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.emailTextField = nil;
    self.passwordTextField = nil;
    self.firstNameTextField = nil;
    self.lastNameTextField = nil;
    self.phoneTextField = nil;
    self.descriptionLabel = nil;
    self.termsOfServiceLabel = nil;
    self.addPhotoButton = nil;
    self.registerScrollView = nil;
}

- (void)dealloc {
    self.avatar = nil;
    
    [emailTextField release];
    [passwordTextField release];
    [firstNameTextField release];
    [lastNameTextField release];
    [phoneTextField release];
    [descriptionLabel release];
    [termsOfServiceLabel release];
    [addPhotoButton release];
    [registerScrollView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods
- (void)resignKeyboard {
    [emailTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    [firstNameTextField resignFirstResponder];
    [lastNameTextField resignFirstResponder];
    [phoneTextField resignFirstResponder];
    [registerScrollView setContentOffset:CGPointMake(0, 0) animated:YES];    
}

#pragma mark - Action methods
- (IBAction)cancelButtonPressed:(id)sender {
    [self resignKeyboard];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)doneButtonPressed:(id)sender {
    [self resignKeyboard];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)createButtonPressed:(id)sender {
    [self resignKeyboard];
    
    // Validate data
    NSString *email = emailTextField.text;
    NSString *password = passwordTextField.text;
    NSString *firstName = firstNameTextField.text;
    NSString *lastName = lastNameTextField.text;
    NSString *phoneNumber = phoneTextField.text;
    
    NSString *errorMessage = nil;
    NSInteger tag = 0;
    
    if (email.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your email", @"");
        tag = AlertViewTagEmailMissing;
    }
    else if (![Global isValidEmail:email]) {
        errorMessage = NSLocalizedString(@"Email is invalid", @"");
        tag = AlertViewTagEmailInvalid;
    }
    else if (password.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your password", @"");
        tag = AlertViewTagPasswordMissing;
    }
    else if (firstName.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your first name", @"");
        tag = AlertViewTagFirstNameMissing;
    }
    else if (lastName.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your last name", @"");
        tag = AlertViewTagLastNameMissing;
    }
    
    if (errorMessage != nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error message", @"")
                                                            message:errorMessage
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                                  otherButtonTitles:nil];
        alertView.tag = tag;
        [alertView show];
        [alertView release];
        return;
    }
    
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Creating..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:email forKey:kEmail];
    [params setObject:password forKey:kPassword];
    [params setObject:firstName forKey:kFirstName];
    [params setObject:lastName forKey:kLastName];
    [params setObject:phoneNumber forKey:kPhone];
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:kDeviceToken];
    [params setObject:deviceToken forKey:kDeviceToken];
    
    if (avatar != nil) {
        NSData *imageData = UIImageJPEGRepresentation(avatar, 1.0);
        [params setObject:imageData forKey:kPhoto];
    }
    
    [TNHRequestHelper sendPostRequest:kRegisterAccountUrl
                              withTag:RequestTagRegisterAccount
                               params:params
                             delegate:self];
}

- (IBAction)addPhotoButtonPressed:(id)sender {
    [self resignKeyboard];
    UIActionSheet *chooseAvatarASheet =[[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"Add photo", @"")
                                                                   delegate:self
                                                          cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
                                                     destructiveButtonTitle:nil
                                                          otherButtonTitles:NSLocalizedString(@"Take Picture", @""), NSLocalizedString(@"Choose from Library", @""), nil];
    [chooseAvatarASheet showInView:self.view];
    [chooseAvatarASheet release];
}

- (IBAction)showTermsOfService:(id)sender {
    [self resignKeyboard];
    TermsOfServiceViewController *termsOfServiceViewController = [[TermsOfServiceViewController alloc] initWithNibName:@"TermsOfServiceViewController" bundle:nil];
    [self.navigationController pushViewController:termsOfServiceViewController animated:YES];
    [termsOfServiceViewController release];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    switch (alertView.tag) {
        case AlertViewTagEmailMissing:
        case AlertViewTagEmailInvalid:
            [emailTextField becomeFirstResponder];            
            break;
        case AlertViewTagPasswordMissing:
            [passwordTextField becomeFirstResponder];
            break;
        case AlertViewTagFirstNameMissing:
            [firstNameTextField becomeFirstResponder];
            break;
        case AlertViewTagLastNameMissing:
            [lastNameTextField becomeFirstResponder];
            break;
        default:
            break;
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex != [actionSheet cancelButtonIndex]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        switch (buttonIndex) {
            case ButtonTagTakePicture:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                }
                else {
                    [imagePicker release];
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning message", @"")
                                                                        message:NSLocalizedString(@"Camera is not available", @"")
                                                                       delegate:nil
                                                              cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                                              otherButtonTitles:nil];
                    [alertView show];
                    [alertView release];
                    return;
                }
                break;
            case ButtonTagChooseFromLibrary:
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                break;
        }
        [self presentModalViewController:imagePicker animated:YES];
        [imagePicker release];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (![Global isIphone5]) {
        if (textField.tag == kEmailIndex || textField.tag == kPasswordIndex) {
            [registerScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        else {
            [registerScrollView setContentOffset:CGPointMake(0, 60) animated:YES];
        }        
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    switch (textField.tag) {
        case kEmailIndex:
            [passwordTextField becomeFirstResponder];
            break;
        case kPasswordIndex:
            [firstNameTextField becomeFirstResponder];
            break;
        case kFirstNameIndex:
            [lastNameTextField becomeFirstResponder];
            break;
        case kLastNameIndex:
            [phoneTextField becomeFirstResponder];
            break;
        case kPhoneIndex:
            break;
        default:
            break;
    }
    return YES;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    self.avatar = image;
    [addPhotoButton setImage:image forState:UIControlStateNormal];
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];    
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSLog(@"data: %@", request.responseString);
    NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];
    NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
    if (errorCode == ErrorCodeNone) {
        NSString *email = emailTextField.text;
        NSString *firstName = firstNameTextField.text;
        NSString *lastName = lastNameTextField.text;
        NSString *phoneNumber = phoneTextField.text;
        
        User *_loggedInUser = [[User alloc] initWithEmail:email firstName:firstName lastName:lastName phoneNumber:phoneNumber avatarImage:avatar];
        _loggedInUser.numberOfPhotos = [[response objectForKey:kNumPhoto] integerValue];
        _loggedInUser.userId = [[response objectForKey:kUserId] integerValue];
        if (![[response objectForKey:kPhoto] isEqual:[NSNull null]]) {
            _loggedInUser.avatarUrl = [response objectForKey:kPhoto];
        }
        if (![[response objectForKey:kSocialId] isEqual:[NSNull null]]) {
            _loggedInUser.socialId = [response objectForKey:kSocialId];            
        }
        _loggedInUser.token = [response objectForKey:kUserToken];
        _loggedInUser.numberOfLikes = [[response objectForKey:kNumLike] integerValue];
        _loggedInUser.numberOfFollowers = [[response objectForKey:kNumFollower] integerValue];
        [GruphotoAppDelegate sharedDelegate].loggedInUser = _loggedInUser;
        [_loggedInUser release];
        
        InstructionViewController *instructionViewController = [[InstructionViewController alloc] initWithNibName:@"InstructionViewController" bundle:nil];
        instructionViewController.instructionIndex = 1;
        self.navigationController.navigationBarHidden = YES;
        [self.navigationController pushViewController:instructionViewController animated:YES];
        [instructionViewController release];
    }
    else {
        NSString *errorMessage = [response objectForKey:kErrorMessage];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Register error"
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];    
}

@end
